namespace Day22EF.Data.Migrations
{
    using Day22EF.Data.Models;
    using Microsoft.AspNet.Identity;
    using Microsoft.AspNet.Identity.EntityFramework;
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;

    internal sealed class Configuration : DbMigrationsConfiguration<Day22EF.Data.HeroDbContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
        }

        protected override void Seed(Day22EF.Data.HeroDbContext context)
        {
            UserStore<User> userStore = new UserStore<User>(context);
            UserManager<User> userManager = new UserManager<User>(userStore);

            User superMan = null;

            userManager.Create(new User
            {
                UserName = "SuperMan"
            }, "123456");

            superMan = userManager.FindByName("SuperMan");

            context.PowerTypes.AddOrUpdate(p => p.Name,
                new PowerType() { Name = "Flying" },
                new PowerType() { Name = "Human"}
            );

            context.SaveChanges();

            context.Powers.AddOrUpdate(p => p.Name,
                new Power() { Name = "Flight of the Navigator", PowerTypeId = 1, UserId = superMan.Id }
            );

            context.Affiliations.AddOrUpdate(a => a.Name,
                new Affiliation() { Name = "Justice League" }
            );

            context.SaveChanges();

            if (!context.AffiliationUsers.Any(a => a.UserId == superMan.Id && a.Affiliation.Name == "Justice League"))
            {
                context.AffiliationUsers.Add(new AffiliationUser
                {
                    AffiliationId = 1,
                    UserId = superMan.Id
                });

                context.SaveChanges();
            }
        }
    }
}
